package com.sunseagear.wind.common.utils.excel;

import com.sunseagear.common.utils.DateUtils;
import com.sunseagear.common.utils.FileUtils;
import com.sunseagear.common.utils.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class ExcelUtils {
    /**
     * 导入数据
     * @param file
     * @param cls
     * @param headerNum
     * @param sheetIndex
     * @throws IOException
     * @throws InstantiationException
     * @throws IllegalAccessException
     */
    public static <T> List<T> importData(MultipartFile file, Class<T> cls, int headerNum, int sheetIndex) throws IOException, InstantiationException, IllegalAccessException {
        ImportExcel ei = new ImportExcel(file, headerNum, sheetIndex);
        return ei.getDataList(cls);
    }

    /**
     * 下载模板
     *
     * @param sheetName
     * @param cls
     * @return
     * @throws IOException
     */
    public static <T> HashMap<String, Object> template(String sheetName, Class<T> cls) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            List<T> list = new ArrayList<>();
            new ExportExcel(sheetName, cls, ExportExcel.TEMPLATE).setDataList(list).write(bos);
            byte[] bytes = bos.toByteArray();
            String bytesRes = StringUtils.bytesToHexString2(bytes);
            String fileName = sheetName + "数据模板" + DateUtils.getDate("yyyyMMddHHmmss");
            HashMap<String, Object> result = new HashMap<>();
            result.put("bytes", bytesRes);
            result.put("title", fileName);
            return result;
        } finally {
            FileUtils.safeCloseOutputStream(bos);
        }


    }

    /**
     * 导出数据
     *
     * @param list
     * @param sheetName
     * @param cls
     * @return
     * @throws IOException
     */
    public static <T> HashMap<String, Object> export(List<T> list, String sheetName, Class<T> cls) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try{
            new ExportExcel(sheetName, cls).setDataList(list).write(bos);
            byte[] bytes = bos.toByteArray();
            String bytesRes = StringUtils.bytesToHexString2(bytes);
            String fileName = sheetName + "数据模板" + DateUtils.getDate("yyyyMMddHHmmss");
            HashMap<String, Object> result = new HashMap<>();
            result.put("bytes", bytesRes);
            result.put("title", fileName);
            return result;
        }finally {
            FileUtils.safeCloseOutputStream(bos);
        }
    }
}
